package comm

import (
	"fmt"
	"github.com/360EntSecGroup-Skylar/excelize"
	"imooc.com/demo_pms/conf"
	"strconv"
)

// iris有解析form表单，但如果参数不存在，返回某个默认值的
// 	执行指定的Sql语句，并把结果映射到结构体。有时，当选择内容或者条件比较复杂时，
// 	可以直接使用Sql，例:engine.SQL("select * from table").Find(&beans)
func NewSelectSql(strs []string) string {
	var rs string = conf.Sql
	l1 := len(rs + " where ")
	j := 0 //where 标志位，标志where加了没，只加1次
	for i, str := range strs {
		if str == "" {
			continue
		}
		if j == 0 {
			rs += " where "
			j++
		}
		if l1 != len(rs) {
			rs += " and "
		}
		switch {
		case i >= 1 && i <= 3:
			rs += conf.MatchList[i] + `"` + str + `"`
		default:
			rs += conf.MatchList[i] + str
		}
	}

	// 按部门分组，工资从小到大排序
	rs += " and a.sys_status=1 order by b.wages asc"
	return rs
}

func StrToInt(str string) int {
	i, _ := strconv.Atoi(str)
	return i
}

func SexToInt(sex string) int {
	if sex == "男" {
		return 1
	}
	return 2
}

func FormatOutput(data map[string][]byte) string {
	gender := "女"
	if string(data["sex"]) == "1" {
		gender = "男"
	}
	rs := fmt.Sprintf("%12s |%12s |%12s |%12s |%12s |%12s |%12s",
		data["work_id"],
		data["name"],
		gender,
		data["part"],
		data["occupation"],
		data["time"],
		data["wages"],
	)
	return rs
}

func SliceMapToSliceString(data []map[string][]byte) []string {
	one := fmt.Sprintf("%12s |%12s |%12s |%12s |%12s |%12s |%12s",
		"工号", "姓名", "性别", "部门", "职业", "发薪时间", "工资")
	rs := []string{one}
	n := len(data)
	for i := 0; i < n; i++ {
		rs = append(rs, FormatOutput(data[i]))
	}
	return rs
}

func SliceMapToExcel(dataList []map[string][]byte) *excelize.File {
	file := excelize.NewFile()
	// 设置第一行值
	firstRow := []string{"工号", "姓名", "性别", "部门", "职业", "发薪时间", "工资"}
	file.SetSheetRow("Sheet1", "A1", &firstRow) //传递切片地址
	n := len(dataList)
	for i := 0; i < n; i++ {
		data := dataList[i]
		row := fmt.Sprintf("A%d", i+2)
		gender := "女"
		if string(data["sex"]) == "1" {
			gender = "男"
		}
		buf := []interface{}{
			data["work_id"],
			data["name"],
			gender,
			data["part"],
			data["occupation"],
			data["time"],
			data["wages"],
		}
		file.SetSheetRow("Sheet1", row, &buf)
	}
	return file
}
